package com.fly.push.web;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Flux;

/**
 * 基于定时器实现SSE推送
 * 
 */
@Slf4j
@CrossOrigin
@RestController
public class StreamSseController
{
    AtomicInteger counter = new AtomicInteger(0);
    
    @GetMapping("/interval/stream")
    public Flux<ServerSentEvent<Integer>> streamSseMvc()
    {
        return Flux.interval(Duration.ofSeconds(2)) // 间隔
            .map(seq -> ServerSentEvent.<Integer> builder().data(counter.incrementAndGet()).build()) // 数据
            .takeUntil(event -> event.data() > 100) // 停止条件
            .doOnComplete(() -> log.info("complete"));
    }
}